package com.okq.dao;

import com.okq.dao.base.Impl.BaseDao;
import com.okq.entity.Dict;
import com.okq.util.page.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述 : 数据字典Dao
 * 作者 : zdl
 * 日期 : 2017/6/28 17:39
 */
@Repository
public class DictDao extends BaseDao {

    public void saveDict(Dict dict) {
        super.save(dict);
    }

    public void deleteDict(Dict dict) {
        super.delete(dict);
    }

    public void updateDict(Dict dict) {
        super.update(dict);
    }

    public void saveOrUpdateDict(Dict dict) {
        super.saveOrUpdate(dict);
    }

    public Dict getDictById(String id) {
        return (Dict) super.get(Dict.class, id);
    }

    public List<Dict> listAllDict() {
        String hql = "FROM Dict WHERE isDelete = 0 ";
        return super.find(hql);
    }

    public Page<Dict> pageByDict(Page<Dict> page, Dict dict) {
        StringBuilder hqlSb = new StringBuilder();
        hqlSb.append("FROM Dict d WHERE d.isDelete = 0 ");
        if (dict != null) {
            Map<String, Object> param = new HashMap<>();
            String name = dict.getName();
            if (StringUtils.isNotBlank(name)) {
                hqlSb.append(" AND d.name LIKE ?1 ");
                param.put("1", "%" + name + "%");
            }
            String type = dict.getType();
            if (StringUtils.isNotBlank(type)) {
                hqlSb.append(" AND d.type = ?2 ");
                param.put("2", type);
            }
            hqlSb.append(" ORDER BY d.createTime DESC ");
            return super.findByPage(page, hqlSb.toString(), param);
        }
        return page;
    }

    /**
     * 查询同一种类型数据字典集合
     *
     * @param type 类型
     * @return list
     */
    public List<Dict> listDictByType(String type) {
        if (StringUtils.isNotBlank(type)) {
            String hql = "FROM Dict WHERE isDelete = 0 AND type = '" + type + "' ";
            return super.find(hql);
        }
        return null;
    }

    public String getDictByValueAndType(Integer value, String type) {
        String name = "";
        if (value != null && StringUtils.isNotBlank(type)) {
            String hql = "FROM Dict WHERE isDelete = 0 AND value = ?1 AND type = ?2 ";
            Map<String, Object> param = new HashMap<>();
            param.put("1", value);
            param.put("2", type);
            Dict d = (Dict) super.get(hql, param);
            if (d != null) {
                name = StringUtils.defaultString(d.getName(), "");
            }
        }
        return name;
    }

}
